﻿using OAuth2Authorizer.Serialization;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text;

namespace OAuth2Authorizer.Framework
{
    internal class DefaultAuthorizer : AuthorizerBase, IAuthorizer
    {
        private static readonly string AuthorizeUrlTemplate = "{0}?response_type={1}&client_id={2}&redirect_uri={3}&state={4}";
        private static readonly string AuthType = "code";
        private static readonly string GrantTypeValue = "authorization_code";

        internal string AuthorizeUrl { get; set; }
        internal string TokenUrl
        {
            get { return _tokenUrl; }
            set { _tokenUrl = value; }
        }
        
        public DefaultAuthorizer() : base(string.Empty) { }

        protected override string GetAuthorizeUrlInternal(string appKey, string redirectUrl, string state)
        {
            return string.Format(AuthorizeUrlTemplate, AuthorizeUrl, AuthType, appKey, redirectUrl, state);
        }

        protected override NameValueCollection GetTokenRequestParameters(string appKey, string appSecret, string redirectUrl, string code)
        {
            var parameters = new NameValueCollection();
            parameters.Add("code", code);
            parameters.Add("grant_type", GrantTypeValue);
            parameters.Add("client_id", appKey);
            parameters.Add("client_secret", appSecret);
            parameters.Add("redirect_uri", redirectUrl);
            return parameters;
        }

        protected override AccessTokenResponse GetResponseObject(Stream stream, string contentType)
        {
            var serializer = SerializerFactory.CreateSerializer<AccessTokenResponse>(contentType);
            return serializer.ReadObject(stream);
        }
    }
}
